import traceback

from django.core import serializers
import json


from django.http import JsonResponse
from django.shortcuts import render,HttpResponse

# Create your views here.
from django.utils.decorators import method_decorator
from django.views import View
from django.views.decorators.csrf import csrf_exempt,csrf_protect

# @csrf_protect #单独为某个视图添加csrf验证
from app.models import User


from rest_framework.serializers import  Serializer
from rest_framework.response import Response
from rest_framework.request import Request
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView


@csrf_exempt   #为某个视图免除csrf验证
def user(request):
    if request.method=='GET':
        # name=request.GET.get('name')
        print('GET success 查询')
        return HttpResponse('GET success')
    elif request.method=='POST':
        print('POST success 添加')
        return HttpResponse('POST success')
    elif request.method=='PUT':
        print('PUT success 修改')
        return HttpResponse('PUT success')
    elif request.method=='DELETE':
        print('DELETE success 删除')
        return HttpResponse('DELETE success')

"""
单条:获取单条,所有,添加单个,删除单个,整体更新单个
"""


#类视图免除csrf验证的方法
@method_decorator(csrf_exempt,name='dispatch')
#django  类视图的定义方法
class Userview(View):
    """
    类视图内部通过请求的方法来匹配打队友的内部的函数,从而进行对应的处理
    """
    def get(self,request,*args,**kwargs):
        #提供查询单个或多个用户的操作
        id=kwargs.get('id')
        print('class GET success 查询')
        print(id)
        if id:
            user=User.objects.filter(id=id).values('name','password').first()
            print(user)
            user1=User.objects.all()
            # res=json.loads(serializers.serialize('json',user))
            res1=json.loads(serializers.serialize('json',user1))

            # print(res)
            if user:
                return JsonResponse({
                    'status':200,
                    'message':"查询单个成功",
                    "result":user
                })

            else:
                user1 = User.objects.all().values('name','password').all()
                # res1 = json.loads(serializers.serialize('json', user1))

                return JsonResponse({
                    'status': 200,
                    'message': "查询全部成功",
                    "result": list(user1)
                })
        else:
            return JsonResponse({
                'status': 500,
                'message': "查询失败",

        })
    def post(self, request, *args, **kwargs):
        #新增数据
        name=request.POST.get('name')
        password=request.POST.get('password')
        try:
            user_new=User.objects.create(name=name,password=password)
            if user_new:
                return JsonResponse({
                    'status': 200,
                    'message': "添加一条信息成功",
                    "result": list(User.objects.all().values('name','password').all())
                })
        except:
            return JsonResponse({
                'status': 500,
                'message': "添加一条信息失败",

            })


    def put(self, request, *args, **kwargs):

        print('class PUT success 修改')
        return HttpResponse('class PUT success')
    def delete(self, request, *args, **kwargs):

        print('class DELETE success 删除')
        return HttpResponse('class DELETE success')

#基于drf的视图
#自带了免除csrf认证的方法,基于as_view,(调用父类的as_view方法)
class Userapi(APIView):
    def get(self,request,*args,**kwargs):
        id = kwargs.get('id')
        if id:
            user=User.objects.filter(id=id).values('name','password').first()
            print(user)
            user1=User.objects.all()
            # res=json.loads(serializers.serialize('json',user))
            res1=json.loads(serializers.serialize('json',user1))

            # print(res)
            if user:
                return JsonResponse({
                    'status':200,
                    'message':"查询单个成功",
                    "result":user
                })

            else:
                user1 = User.objects.all().values('name','password').all()
                # res1 = json.loads(serializers.serialize('json', user1))

                return JsonResponse({
                    'status': 200,
                    'message': "查询全部成功",
                    "result": list(user1)
                })
        else:
            return JsonResponse({
                'status': 500,
                'message': "查询失败",

        })



    def post(self,request,*args,**kwargs):
        """
        # post请求传递参数的形式  form-data  www-urlencoded  json
        print(request._request.POST)  # Django 原生的request对象
        print(request.POST)  # DRF 封装后的request对象
        # 可以获取多种格式的参数 DRF 扩展的请回去参数  兼容性最强,可以获取json的数据,而上面的两种却不行
        print(request.data)
        """
        name = request.data.get('name')
        password = request.data.get('password')
        print('这是新增的用post')
        print(name,password)
        try:
            user_new = User.objects.create(name=name, password=password)
            if user_new:
                return JsonResponse({
                    'status': 200,
                    'message': "添加一条信息成功",
                    "result": list(User.objects.all().values('name', 'password').all())
                })
        except:
            return JsonResponse({
                'status': 500,
                'message': "添加一条信息失败",

            })

